package logic

import (
	"context"
	"errors"
	"video-hubs/model/cache"
	"video-hubs/model/mysql"

	"video-hubs/videorpc/internal/svc"
	"video-hubs/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *videorpc.UpdateRequest) (*videorpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindUser(mysql.DB, in.Username); err != nil {
		return nil, err
	}

	data := mysql.User{
		Username: user.Username,
		Password: in.Newpassword,
	}
	if err := data.UpdateUser(mysql.DB, in.Username); err != nil {
		return nil, err
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Username).Result()
	if result != in.SendSmsNick {
		return nil, errors.New("验证码错误")
	}
	return &videorpc.UpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
